package handler

import (
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"net/http"
	"fmt"
	"github.com/FileClassifyWeb/internal/service"
	"sync"
	"os"
	"path/filepath"
)

var upgrader = websocket.Upgrader{
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

var (
	wsConnections = make(map[string]*wsConnection)
	wsLock       sync.RWMutex
)

type wsConnection struct {
	conn         *websocket.Conn
	progressChan chan int
	messageChan  chan string
}

func newWSConnection(conn *websocket.Conn) *wsConnection {
	return &wsConnection{
		conn:         conn,
		progressChan: make(chan int),
		messageChan:  make(chan string),
	}
}

func addWSConnection(connID string, conn *wsConnection) {
	wsLock.Lock()
	defer wsLock.Unlock()
	wsConnections[connID] = conn
}

func getWSConnection(connID string) (*wsConnection, bool) {
	wsLock.RLock()
	defer wsLock.RUnlock()
	conn, exists := wsConnections[connID]
	return conn, exists
}

func removeWSConnection(connID string) {
	wsLock.Lock()
	defer wsLock.Unlock()
	delete(wsConnections, connID)
}

// IndexHandler 处理首页请求
func IndexHandler(c *gin.Context) {
	c.HTML(http.StatusOK, "index.html", gin.H{
		"title": "文件分类系统",
	})
}

// WebSocketHandler 处理WebSocket连接
func WebSocketHandler(c *gin.Context) {
	ws, err := upgrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}
	defer ws.Close()

	wsConn := newWSConnection(ws)
	connID := c.Request.Header.Get("Sec-WebSocket-Key")
	addWSConnection(connID, wsConn)
	defer removeWSConnection(connID)

	go wsConn.writeMessages()

	// 保持连接
	for {
		_, _, err := ws.ReadMessage()
		if err != nil {
			break
		}
	}
}

func (w *wsConnection) writeMessages() {
	for {
		select {
		case progress := <-w.progressChan:
			w.conn.WriteJSON(gin.H{
				"type":     "progress",
				"progress": progress,
			})
		case message := <-w.messageChan:
			w.conn.WriteJSON(gin.H{
				"type":    "message",
				"message": message,
			})
		}
	}
}

// ClassifyHandler 处理文件分类请求
func ClassifyHandler(c *gin.Context) {
	var req service.ClassifyRequest
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 获取所有活跃的WebSocket连接
	wsLock.RLock()
	activeConns := make([]*wsConnection, 0, len(wsConnections))
	for _, conn := range wsConnections {
		activeConns = append(activeConns, conn)
	}
	wsLock.RUnlock()

	if len(activeConns) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error": "没有活跃的WebSocket连接"})
		return
	}

	// 使用第一个活跃的连接
	wsConn := activeConns[0]

	// 创建分类服务
	classifyService := service.NewClassifyService(wsConn.progressChan, wsConn.messageChan)

	// 异步执行分类
	go func() {
		if err := classifyService.Classify(&req); err != nil {
			wsConn.messageChan <- fmt.Sprintf("分类失败: %v", err)
		}
	}()

	c.JSON(http.StatusOK, gin.H{
		"status":  "success",
		"message": "分类任务已开始",
	})
}

// SelectDirHandler 处理目录选择请求
func SelectDirHandler(c *gin.Context) {
	// 获取用户主目录
	homeDir, err := os.UserHomeDir()
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 获取请求中的当前目录参数
	currentDir := c.Query("dir")
	if currentDir == "" {
		currentDir = homeDir
	}

	// 读取目录内容
	entries, err := os.ReadDir(currentDir)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
		return
	}

	// 构建目录列表
	var dirs []map[string]interface{}
	
	// 添加上级目录（如果不是根目录）
	if currentDir != "/" {
		dirs = append(dirs, map[string]interface{}{
			"name": "..",
			"path": filepath.Dir(currentDir),
			"type": "dir",
		})
	}

	// 添加当前目录的子目录
	for _, entry := range entries {
		if entry.IsDir() {
			fullPath := filepath.Join(currentDir, entry.Name())
			dirs = append(dirs, map[string]interface{}{
				"name": entry.Name(),
				"path": fullPath,
				"type": "dir",
			})
		}
	}

	c.JSON(http.StatusOK, gin.H{
		"currentDir": currentDir,
		"dirs":       dirs,
	})
} 